package com.sinoglobal.shakeprize.utils;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import android.os.Handler;
import android.os.Looper;


import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @author temulu
 * @createdate 2015-8-26下午2:06:37
 * @Description 访问网络工具类
 */
public class OKhttpUtil {
    private static OkHttpClient.Builder builder = new OkHttpClient.Builder();
    private static OkHttpClient client = builder.connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .build();
    //    private static OkHttpClient client = new OkHttpClient();
    private static final MediaType JSON = MediaType
            .parse("application/json; charset=utf-8");
    private static List<Callback> tags = new ArrayList<Callback>();
    private static Handler handler = new Handler(Looper.getMainLooper());


    /**
     * 异步get访问网络
     *
     * @param url
     * @throws MalformedURLException
     */
    public static void enqueue(String url, final ResponseCallback rCallback) {

        if (url.contains("{")) {
            url = url.replace("{", "%7b").replace("}", "%7d");
        }
        ItktLog.e("okhttp-->URL:" + url);
        final Request request;
        request = new Request.Builder().url(url).build();
        Callback callback = new Callback() {
            @Override
            public void onFailure(final Call call, final IOException e) {
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        rCallback.onFailure(call.request(), e);
                    }
                });
            }

            @Override
            public void onResponse(final Call call, Response response) throws IOException {
                if (response != null) {
                    json = response.body().string();
                }
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            rCallback.onResponse(json);
                        } catch (IOException e) {
                            onFailure(call, e);
                        }
                    }
                });

            }

            String json = "";


        };

        client.newCall(request).enqueue(callback);
        tags.add(callback);
    }

    public interface ResponseCallback {
        public abstract void onFailure(Request paramRequest,
                                       IOException paramIOException);

        public abstract void onResponse(String json) throws IOException;
    }

    /**
     * 异步post访问网络
     *
     * @param url
     * @param json
     * @param callback
     */
    public static void enqueue(String url, String json, final Callback callback) {
        RequestBody body = RequestBody.create(JSON, json);
        final Request request = new Request.Builder().post(body).url(url)
                .tag(callback).build();
        client.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(final Call call, final IOException e) {
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        callback.onFailure(call, e);
                    }
                });

            }

            @Override
            public void onResponse(final Call call, final Response response) throws IOException {
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            callback.onResponse(call, response);
                        } catch (IOException e) {
                            onFailure(call, e);
                        }
                    }
                });
            }


        });
        tags.add(callback);

    }

    // /**
    // * 销毁所有链接
    // */
    // public static void cancle() {
    // for (int i = 0; i < tags.size(); i++) {
    // client.cancel(tags.get(i));
    // }
    // }

}
